package com.macro.mall.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.enums.CellDataTypeEnum;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class LocalDateTimeConverter implements Converter<LocalDateTime> {

    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");

    @Override
    public Class<LocalDateTime> supportJavaTypeKey() {
        return LocalDateTime.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public LocalDateTime convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        String stringValue = cellData.getStringValue();
        if (stringValue.length() == 10) { // yyyy-MM-dd
            return LocalDateTime.parse(stringValue, DATE_FORMATTER);
        } else if (stringValue.length() == 19) { // yyyy-MM-dd HH:mm:ss
            return LocalDateTime.parse(stringValue, DATETIME_FORMATTER);
        } else {
            throw new IllegalArgumentException("不支持的日期格式: " + stringValue);
        }
    }

    @Override
    public CellData<String> convertToExcelData(LocalDateTime value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        if (value.getHour() == 0 && value.getMinute() == 0 && value.getSecond() == 0) {
            return new CellData<>(value.format(DATE_FORMATTER));
        } else {
            return new CellData<>(value.format(DATETIME_FORMATTER));
        }
    }
}
